package notebook.client;
//http://www.ibm.com/developerworks/cn/web/wa-lo-gwtjson/

import notebook.client.RichTextToolBar.RichTextToolbar1;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class Notebook extends PopupPanel{
	String[] sayingKeywords = new String[]{"名人","励志","政治","教育","男女","段子"};
	String[] articleKeywords = new String[]{"科学","历史","宗教","小说","名家","原创","时评"};
	String[] picKeywords = new String[]{"人物","照片","娱乐","事件","受限"};
	String[] videoKeywords = new String[]{"教学","娱乐","受限"};
	String[] websiteKeywords = new String[]{"教学","娱乐","受限"};
	String[] relativeKeywords = new String[]{"家庭成员","父老乡亲","同学","同事","朋友"};
	TabPanel tabPanel = new TabPanel();

	public Notebook() {
		super(false);
		setWidget(tabPanel);
		setPopupPositionAndShow(new PopupPanel.PositionCallback() {
	          public void setPosition(int offsetWidth, int offsetHeight) {
	            int left = (Window.getClientWidth() - offsetWidth) / 2;
	            setPopupPosition(left, 0);
	          }
	        });
		this.setAnimationEnabled(true);
	}

	protected VerticalPanel readSaying(String keyword, int ti){
		VerticalPanel vp = new VerticalPanel();
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL()+URL.encode("saveDTOService")+"?txt="+keyword);
		try {
			  builder.sendRequest(null, new getContentRequestCallback(vp, ti));
			} catch (RequestException e) {}
		return vp;
	}
	protected VerticalPanel writeSaying(){
		VerticalPanel vp = new VerticalPanel();
		final HorizontalPanel keywordWritePanel = getKeywordPanel(0);
		vp.add(keywordWritePanel);
		final RichTextToolbar1 rttb1 = new RichTextToolbar1();
		rttb1.getRichTextPanel().setHeight("70px");
		vp.add(rttb1);
		
		Button save = new Button("保存"); 
		HorizontalPanel hp = new HorizontalPanel();
		hp.add(save);
		hp.add(getHideButton());
		vp.add(hp); 
		save.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				JSONObject inputs = new JSONObject();
				inputs.put("content",new JSONString(rttb1.getRichTextPanel().getHTML()));
				JSONArray suitesArray = new JSONArray();
				suitesArray.set(0, new JSONString("语录"));
				TextBox temp6 = (TextBox)keywordWritePanel.getWidget(7);
				inputs.put("userKeyword", new JSONString(temp6.getText()));
				int index=1;
				for(int i=1;i<= sayingKeywords.length;i++){
					CheckBox temp = (CheckBox)keywordWritePanel.getWidget(i);
					if(temp.getValue()){
						suitesArray.set(index++, new JSONString(sayingKeywords[i-1]));
					}
				}
				inputs.put("fixedKeyword", suitesArray);
				String saveMessage = FieldVerifier.hasContent(inputs);
				if(saveMessage.equals(""))
				{
					RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, GWT.getModuleBaseURL()+URL.encode("saveDTOService"));
					try {
						  builder.sendRequest(inputs.toString(), new startSaveRequestCallback());
						} catch (RequestException e) {
						}
				}
				else{
					Window.alert(saveMessage);
				}
			}});
		return vp;
	}

	protected VerticalPanel getArticle(){
		VerticalPanel vp = new VerticalPanel();
		final HorizontalPanel keywordWritePanel = getKeywordPanel(1);
		vp.add(keywordWritePanel);
		
		HorizontalPanel hp = new HorizontalPanel();
		hp.setWidth("870px");
		Label title = new Label("标题：");
		final TextBox textBox_1 = new TextBox();
		hp.add(title);
		hp.setCellWidth(title, "47px");
		title.setWidth("47px");hp.add(textBox_1);
		textBox_1.setWidth("100%");vp.add(hp);
		
		final RichTextToolbar1 rttb1 = new RichTextToolbar1();
		rttb1.getRichTextPanel().setHeight("400px");
		vp.add(rttb1);

		Button save = new Button("保存"); 
		HorizontalPanel hp1 = new HorizontalPanel();
		hp1.add(save);
		hp1.add(getHideButton());
		vp.add(hp1);
		save.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				JSONObject inputs = new JSONObject();
				inputs.put("content",new JSONString(rttb1.getRichTextPanel().getHTML()));
				inputs.put("title",new JSONString(textBox_1.getText()));
				JSONArray suitesArray = new JSONArray();
				suitesArray.set(0, new JSONString("文章"));
				int index=1;
				for(int i=1;i<= articleKeywords.length;i++){
					CheckBox temp = (CheckBox)keywordWritePanel.getWidget(i);
					if(temp.getValue()){
						suitesArray.set(index++, new JSONString(articleKeywords[i-1]));
					}
				}
				inputs.put("fixedKeyword", suitesArray);
				TextBox temp7 = (TextBox)keywordWritePanel.getWidget(8);
				inputs.put("userKeyword", new JSONString(temp7.getText()));
				String saveMessage = FieldVerifier.isValidArticle(inputs);
				if(saveMessage.equals(""))
				{
					RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode("saveDTOService"));
					try {
						  builder.sendRequest(inputs.toString(), new startSaveRequestCallback());
						} catch (RequestException e) {
						}
				}
				else{
					Window.alert(saveMessage);
				}
			}});
		
		return vp;
	}

	
	protected VerticalPanel getPic(){
		VerticalPanel vp = new VerticalPanel();
		final HorizontalPanel keywordWritePanel = getKeywordPanel(2);
		vp.add(keywordWritePanel);
		
		HorizontalPanel hp = new HorizontalPanel();
		hp.setWidth("870px");
		Label title = new Label("标题：");
		final TextBox textBox_1 = new TextBox();
		hp.add(title);
		hp.setCellWidth(title, "47px");
		title.setWidth("47px");hp.add(textBox_1);
		textBox_1.setWidth("100%");vp.add(hp);
		HorizontalPanel urlAddress = new HorizontalPanel();
		urlAddress.setWidth("870px");
		Label addr =  new Label("网址：");
		urlAddress.add(addr);
		urlAddress.setCellWidth(addr, "47px");
		final TextBox tb = new TextBox();
		tb.setWidth("100%");
		urlAddress.add(tb);
		vp.add(urlAddress);

		Button save = new Button("保存"); 
		HorizontalPanel hp1 = new HorizontalPanel();
		hp1.add(save);
		hp1.add(getHideButton());
		vp.add(hp1);
		save.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				JSONObject inputs = new JSONObject();
				inputs.put("title",new JSONString(textBox_1.getText()));
				inputs.put("url",new JSONString(tb.getText()));
				JSONArray suitesArray = new JSONArray();
				suitesArray.set(0, new JSONString("图片"));
				int index=1;
				for(int i=1;i<= picKeywords.length;i++){
					CheckBox temp = (CheckBox)keywordWritePanel.getWidget(i);
					if(temp.getValue()){
						suitesArray.set(index++, new JSONString(picKeywords[i-1]));
					}
				}
				inputs.put("fixedKeyword", suitesArray);
				TextBox temp5 = (TextBox)keywordWritePanel.getWidget(6);
				inputs.put("fixedKeyword", suitesArray);
				inputs.put("userKeyword", new JSONString(temp5.getText()));
				String saveMessage = FieldVerifier.isValidArticle(inputs);
				if(saveMessage.equals(""))
				{
					RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode("saveDTOService"));
					try {
						  builder.sendRequest(inputs.toString(), new startSaveRequestCallback());
						} catch (RequestException e) {
						}
				}
				else{
					Window.alert(saveMessage);
				}
			}});
		return vp;
	}
	

	
	protected VerticalPanel getVideo(){
		VerticalPanel vp = new VerticalPanel();
		final HorizontalPanel keywordWritePanel = getKeywordPanel(3);
		vp.add(keywordWritePanel);

		HorizontalPanel hp = new HorizontalPanel();
		hp.setWidth("870px");
		Label title = new Label("标题：");
		final TextBox textBox_1 = new TextBox();
		hp.add(title);
		hp.setCellWidth(title, "47px");
		title.setWidth("47px");hp.add(textBox_1);
		textBox_1.setWidth("100%");vp.add(hp);
		HorizontalPanel urlAddress = new HorizontalPanel();
		urlAddress.setWidth("870px");
		Label addr =  new Label("网址：");
		urlAddress.add(addr);
		urlAddress.setCellWidth(addr, "47px");
		final TextBox tb = new TextBox();
		tb.setWidth("100%");
		urlAddress.add(tb);
		vp.add(urlAddress);

		Button save = new Button("保存"); 
		HorizontalPanel hp1 = new HorizontalPanel();
		hp1.add(save);
		hp1.add(getHideButton());
		vp.add(hp1);
		save.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				JSONObject inputs = new JSONObject();
				inputs.put("title",new JSONString(textBox_1.getText()));
				inputs.put("url",new JSONString(tb.getText()));
				JSONArray suitesArray = new JSONArray();
				suitesArray.set(0, new JSONString("视频"));
				int index=1;
				for(int i=1;i<= videoKeywords.length;i++){
					CheckBox temp = (CheckBox)keywordWritePanel.getWidget(i);
					if(temp.getValue()){
						suitesArray.set(index++, new JSONString(videoKeywords[i-1]));
					}
				}
				inputs.put("fixedKeyword", suitesArray);
				TextBox temp3 = (TextBox)keywordWritePanel.getWidget(4);
				inputs.put("userKeyword", new JSONString(temp3.getText()));
				String saveMessage = FieldVerifier.isValidArticle(inputs);

				if(saveMessage.equals(""))
				{
					RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode("saveDTOService"));
					try {
						  builder.sendRequest(inputs.toString(), new startSaveRequestCallback());
						} catch (RequestException e) {
						}
				}
				else{
					Window.alert(saveMessage);
				}
			}});
		return vp;
	}

	
	protected VerticalPanel getWebSite(){
		VerticalPanel vp = new VerticalPanel();
		final HorizontalPanel keywordWritePanel = getKeywordPanel(4);
		vp.add(keywordWritePanel);

		HorizontalPanel urlAddress = new HorizontalPanel();
		urlAddress.setWidth("870px");
		Label addr =  new Label("网址：");
		urlAddress.add(addr);
		urlAddress.setCellWidth(addr, "47px");
		final TextBox tb = new TextBox();
		tb.setWidth("100%");
		urlAddress.add(tb);
		vp.add(urlAddress);

		Button save = new Button("保存"); 
		HorizontalPanel hp = new HorizontalPanel();
		hp.add(save);
		hp.add(getHideButton());
		vp.add(hp);
		save.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				JSONObject inputs = new JSONObject();
				inputs.put("url",new JSONString(tb.getText()));
				JSONArray suitesArray = new JSONArray();
				suitesArray.set(0, new JSONString("网站"));
				int index=1;
				for(int i=1;i<= websiteKeywords.length;i++){
					CheckBox temp = (CheckBox)keywordWritePanel.getWidget(i);
					if(temp.getValue()){
						suitesArray.set(index++, new JSONString(websiteKeywords[i-1]));
					}
				}
				inputs.put("fixedKeyword", suitesArray);
				TextBox temp3 = (TextBox)keywordWritePanel.getWidget(4);
				inputs.put("userKeyword", new JSONString(temp3.getText()));
				String saveMessage = FieldVerifier.isValidArticle(inputs);
				if(saveMessage.equals(""))
				{
					RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode("saveDTOService"));
					try {
						  builder.sendRequest(inputs.toString(), new startSaveRequestCallback());
						} catch (RequestException e) {
						}
				}
				else{
					Window.alert(saveMessage);
				}
			}});
		return vp;
	}


	
	protected VerticalPanel getRelative(){
		VerticalPanel vp = new VerticalPanel();
		final HorizontalPanel keywordWritePanel = getKeywordPanel(5);
		vp.add(keywordWritePanel);
		
		final RichTextToolbar1 rttb1 = new RichTextToolbar1();
		rttb1.getRichTextPanel().setHeight("70px");
		vp.add(rttb1);

		Button save = new Button("保存"); 
		HorizontalPanel hp = new HorizontalPanel();
		hp.add(save);
		hp.add(getHideButton());
		vp.add(hp);
		save.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				JSONObject inputs = new JSONObject();
				JSONArray suitesArray = new JSONArray();
				suitesArray.set(0, new JSONString("传记"));
				int index=1;
				for(int i=1;i<= relativeKeywords.length;i++){
					CheckBox temp = (CheckBox)keywordWritePanel.getWidget(i);
					if(temp.getValue()){
						suitesArray.set(index++, new JSONString(relativeKeywords[i-1]));
					}
				}
				inputs.put("fixedKeyword", suitesArray);
				TextBox temp5 = (TextBox)keywordWritePanel.getWidget(6);
				inputs.put("userKeyword", new JSONString(temp5.getText()));
				String saveMessage = FieldVerifier.isValidArticle(inputs);
				if(saveMessage.equals(""))
				{
					RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode("saveDTOService"));
					try {
						  builder.sendRequest(inputs.toString(), new startSaveRequestCallback());
						} catch (RequestException e) {
						}
				}
				else{
					Window.alert(saveMessage);
				}
			}});
		return vp;
	}
	private TextBox getUserkeywordTB(){
		TextBox textBox = new TextBox();
		textBox.setTitle("其他关键字如：古典，爱情，作者：曹雪芹，");
		textBox.setSize("200px", "15px");
		return textBox;
	}
	private HorizontalPanel getKeywordPanel(int panelName){
		String[] temp = null;
		switch(panelName){
		case 0:{temp=sayingKeywords;break;}
		case 1:{temp=articleKeywords;break;}
		case 2:{temp=picKeywords;break;}
		case 3:{temp=videoKeywords;break;}
		case 4:{temp=websiteKeywords;break;}
		default :temp=relativeKeywords;
		}
		HorizontalPanel ret = new HorizontalPanel();
		ret.setSize("585px", "100%");
		Label label = new Label("关键字");
		ret.add(label);
		label.setWidth("45px");
		for(String k:temp){
			ret.add(new CheckBox(k));
		}
		ret.add(getUserkeywordTB());
		return ret;
	}
	
	private Button getHideButton(){
		Button hide = new Button("隐藏");
		hide.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				hide();
			}
		});
		return hide;
	}
	private class startSaveRequestCallback implements RequestCallback {
		public void onError(Request request, Throwable exception) {
		}

		public void onResponseReceived(Request request, Response response) {
//		      if (200 == response.getStatusCode()) {
//	         Window.alert("succeed");
//	      } else {
//	    	  Window.alert("failed");
//	      }
		}
	}
	private class getContentRequestCallback implements RequestCallback {
		VerticalPanel vp;
		int tabIndex;
		public getContentRequestCallback(VerticalPanel v,int ti) {
			super();
			tabIndex = ti;
			vp = v;
		}

		public void onError(Request request, Throwable exception) {
		}

		public void onResponseReceived(Request request, Response response) {
		   if (200 == response.getStatusCode()) {
				  HorizontalPanel keywordReadPanel = getKeywordPanel(tabIndex);
				  vp.add(keywordReadPanel);
		    	  String respText = response.getText();
		    	  if(respText.equals(""))return;
					JSONValue respValue = JSONParser.parseLenient(respText);
					JSONArray trArray = respValue.isArray();
					if(trArray.size()>0 && vp!=null){
						for(int i=0;i<trArray.size();i++){
							JSONObject jo = trArray.get(i).isObject();
							CaptionPanel cp = new CaptionPanel(jo.get("UpdateTime").isString().stringValue());
							HTML h = new HTML(jo.get("Content").isString().stringValue());
							cp.setContentWidget(h);
							vp.add(cp);						
						}
					}
	      } 
//		   else {
//	    	  Window.alert("failed");
//	      }
		}
	}
	public void showRead(){
		tabPanel.setSize("90%", "100%");
		tabPanel.clear();
		tabPanel.add(readSaying( "语录",0), "语录");
		tabPanel.add(readSaying( "文章",1), "文章");
		tabPanel.add(readSaying( "图片",2), "图片");
		tabPanel.add(readSaying( "视频",3), "视频");
		tabPanel.add(readSaying( "网站",4), "网站");
		tabPanel.add(readSaying( "传记",5), "传记");
		tabPanel.selectTab(0);
		this.show();
	}
	public void showWrite(){
		tabPanel.setSize("90%", "100%");
		tabPanel.clear();
		tabPanel.add(writeSaying(), "语录");
		tabPanel.add(getArticle(), "文章");
		tabPanel.add(getPic(), "图片");
		tabPanel.add(getVideo(), "视频");
		tabPanel.add(getWebSite(), "网站");
		tabPanel.add(getRelative(), "传记");
		tabPanel.selectTab(0);
		this.show();
	}
	
	public TabPanel getTabPanel() {
		return tabPanel;
	}

}
